package com.google.code;

import java.io.IOException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

import android.util.Log;

public class Socket {

	private int id;
	private String ip;
	private int port;
	private List<String> messages;
	private java.net.Socket socket;
	
	public Socket(String ip, int port)
	{
		this.ip = ip;
		this.port = port;
		this.messages = new ArrayList<String>();
		try {
			socket = new java.net.Socket(ip,port);
			Log.d("HELPER", "CONNECTED");
			(new SocketReader()).start();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void close()
	{
		try {
			this.socket.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}
	
	public String getNextMessage()
	{
		if(this.messages.size() < 0)
			return null;
		String temp = this.messages.get(0);
		this.messages.remove(0);
		return temp;
	}
	
	public void sendMessage(String message)
	{
		if(socket != null)
			if(socket.isConnected())
				try {
					socket.getOutputStream().write(message.getBytes());
				} catch (IOException e) {
					e.printStackTrace();
				}
	}
	
	private class SocketReader extends Thread
	{
		public void run()
		{
			while(true)
			{
				String message = "";
				int inputNum; 
				byte[] tempMessage = new byte[1204];
				try {
					while((inputNum = socket.getInputStream().read(tempMessage)) > 0)
					{
						String temp = new String(tempMessage);
						message += temp.substring(0,inputNum);
						if(socket.getInputStream().available() <= 0) 
							break;
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
				if(message != "")
				{
					String[] parts = message.split("~"); 
					if(parts.length >= 1)
					{
						Log.d("THERM", parts[0]);
						if(parts[0].trim().equals("cur"))
						{
							mainScreen.setCurTemp(Double.parseDouble(parts[1]));
						}
						else if(parts[0].trim().equals("des"))
							mainScreen.setDesiredTemp(Double.parseDouble(parts[1]));
					}
					Log.d("HELPER",message);
				}
			}
		}
	}
}
